package com.peng.leetcode.array;

import java.util.*;

/**
 * AddToArrayForm
 *
 * 989. 数组形式的整数加法
 *
 * @author: lupeng6
 * @create: 2021/1/22 16:14
 */
public class AddToArrayForm {

    public static void main(String[] args) {
        int[] A = {9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
        int K = 1;
        System.out.println(new AddToArrayForm().addToArrayForm(A, K));
    }

    public List<Integer> addToArrayForm(int[] A, int K) {
        Queue<Integer> queue = new LinkedList<>();
        while (K >= 10) {
            int num = K % 10;
            queue.offer(num);
            K = K / 10;
        }
        queue.offer(K);

        boolean flag = false;
        Deque<Integer> stack = new LinkedList<>();

        int index = A.length - 1;

        while (index >= 0 || !queue.isEmpty()) {
            int sum = 0;
            if (!queue.isEmpty()) {
                Integer poll = queue.poll();
                sum += poll;
            }
            if (index >= 0) {
                sum += A[index];
                index--;
            }
            if (flag) {
                sum++;
            }
            if (sum >= 10) {
                flag = true;
                sum = sum % 10;
            } else {
                flag = false;
            }
            stack.push(sum);
        }
        if (flag) {
            stack.push(1);
        }
        return Arrays.asList(stack.toArray(new Integer[0]));
    }


}
